package controller

import (
	"Graphite/model"
	"Graphite/service"
	"Graphite/util"
	"encoding/json"
	"github.com/gin-gonic/gin"
)
func Login(c *gin.Context)  {
	var user model.Login
	if err := c.Bind(&user); err != nil {
		util.Return(c, 200,util.PARA_ERROR, err)
		return
	}
	if err :=util.CheckData(user);err==nil {
		service.Login(c,user)
		return
	} else {
		util.Return(c, 200,util.PARA_ERROR, err)
		return
	}
}

func GetUserByToken(c *gin.Context)  {
	user, exists:= c.Get("user")
	if exists {
		util.Return(c,200,util.SUCCESS,user)
		return
	}
	util.Return(c,200,util.NOT_EXIST,user)
}


func UserInsert(c *gin.Context) {
	var user model.User
	if err := c.Bind(&user); err != nil {
		util.Return(c, 200, util.PARA_ERROR, err)
		return
	}
	if err :=util.CheckData(user);err!=nil {
		util.Return(c, 200, util.PARA_ERROR, err)
		return
	}
	service.UserInsert(c,user)
	return
}


func FindAllUser(c *gin.Context)  {
	jsonStr:=util.Retrieve(c,"user","name","")
	//格式转化成结构体
	var user  []model.User
	_:json.Unmarshal(jsonStr,&user)
	util.Return(c,200,util.SUCCESS,user)
}

func FindAllUserByName(c *gin.Context)  {
	var  key model.Key
	key.Key= c.Query("key")
	jsonStr:=util.Retrieve(c,"user","name",key.Key)
	//格式转化成结构体
	var user  []model.User
	_:json.Unmarshal(jsonStr,&user)
	util.Return(c,200,util.SUCCESS,user)
}


func UserUpdate(c *gin.Context)  {
	var  user model.User
	if err:=c.Bind(&user);err !=nil {
		util.Return(c, 200, util.PARA_ERROR, err)
		return
	}else {
		service.UserUpdate(c,user)
		//util.UpdateOne(c,"user",user,"_id",user.Id)
	}
}

func UserDelete(c *gin.Context)  {
	var user model.User
	if err:=c.Bind(&user);err !=nil {
		util.Return(c,  200,util.PARA_ERROR, err)
		return
	}else {
		util.DeleteOne(c,"user","_id",user.Id)
	}
}



func UserPasswordUpdate(c *gin.Context)  {
	var user model.User
	if err:=c.Bind(&user);err !=nil {
		util.Return(c,  200,util.PARA_ERROR, err)
		return
	}
	if err :=util.CheckData(user);err==nil {
		service.UserPasswordUpdate(c,user)
	} else {
		util.Return(c, 200,util.PARA_ERROR, err)
		return
	}
}



